package com.android.hct.uart_weight_demo;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;

import android_serialport_api.FixSizeLinkedList;

public class WebActivity extends Activity {
    SerialPortUtils serialPortUtils;
    private Handler handler=null;
    byte[] commbuf=new byte[4096];
    int pCommbuf=0;
    int length;
    Spinner spinner_port;
    Button button_open;
    private SerialPortFinder mSerialPortFinder;
    FixSizeLinkedList logList=new FixSizeLinkedList(10);
    String portDevicePath[]=null;

    SharedPreferences sp;
    private WebView webView;
    private LinearLayout llTitle,llPort;
    private EditText etURL;
    private MyJavascriptInterface myJavascriptInterface=new MyJavascriptInterface();
    private static final String defUrl  = "http://192.168.150.39:7778/weight.html";

    SCALENOW scalenow=new SCALENOW();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sp = getApplication().getSharedPreferences("FILE_NAME", Context.MODE_PRIVATE);
        setContentView(R.layout.activity_web);
        //创建属于主线程的handler
        handler=new Handler();
        initView();
        initWB();
        initListener();
        serialPortUtils=new SerialPortUtils();
        //设置读到数据后的操作
        serialPortUtils.setOnDataReceiveListener((buffer, size) -> {
            for(int i = 0; i < size; i++) {
                if (buffer[i] == 0x2){
                    pCommbuf = 0; //判断起始符
                    commbuf=new byte[4096];
                }
                else if ((buffer[i] == 0x0a)||(buffer[i] == 0x03)) {    //判断结束符
                    if(commbuf[pCommbuf-1]==0x0d)pCommbuf-=1;
                    commbuf[pCommbuf]=0;
                    length=pCommbuf;
                    pCommbuf=0;
                    //收到数据后的处理
                    handler.post(() -> {
                        addLog(commbuf);
                        if((commbuf[0]=='S')&&(commbuf[1]=='Z')) {
                            Toast.makeText(WebActivity.this,"归零成功",Toast.LENGTH_SHORT).show();
                        } else {
                            GetWeight(commbuf);
                            showWeightToJS(scalenow.sformatNetWeight);
                        }
                    });

                }
                else commbuf[pCommbuf++]=buffer[i];
            }
        });

        mSerialPortFinder = new SerialPortFinder();
        portDevicePath =mSerialPortFinder.getAllDevicesPath();

        ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, portDevicePath);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner_port.setAdapter(adapter);
        llPort.setVisibility(View.VISIBLE);
        for (int i = 0; i < portDevicePath.length; i++) {
            if (portDevicePath[i].contains("/dev/ttyS1")){
                spinner_port.setSelection(i);
                open();
                llPort.setVisibility(View.GONE);
                break;
            }
        }
    }

    private void open() {
        if(serialPortUtils.serialPortStatus)
        {
            serialPortUtils.closeSerialPort();
            button_open.setText("open");
        } else {
            int selectedItemPosition = spinner_port.getSelectedItemPosition();
            if (selectedItemPosition<0){
                Toast.makeText(getApplicationContext(),"请选择端口",Toast.LENGTH_LONG).show();
                return;
            }
            String s = portDevicePath[selectedItemPosition];
            serialPortUtils.openSerialPort(s, 9600);
            if(serialPortUtils.serialPortStatus)button_open.setText("close");
        }
    }

    private void initView(){
        spinner_port=(Spinner)findViewById(R.id.spinner_port);
        button_open=(Button)findViewById(R.id.button_open);
        llTitle = findViewById(R.id.llTitle);
        llPort= findViewById(R.id.llPort);
        etURL =findViewById(R.id.etURL);
    }

    @SuppressLint("JavascriptInterface")
    private void initWB(){
        webView = findViewById(R.id.wb);
        //声明WebSettings子类
        WebSettings webSettings = webView.getSettings();
        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);
        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        //缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
        //其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
        webView.addJavascriptInterface(myJavascriptInterface,"MyJavascriptInterface");
        webView.loadUrl(getUrl());
        etURL.setText(webView.getUrl());
    }

    private void initListener(){
        webView.setOnLongClickListener(v -> {
            llTitle.setVisibility(llTitle.getVisibility()==View.VISIBLE?View.GONE:View.VISIBLE);
            llPort.setVisibility(llTitle.getVisibility());
            return false;
        });
        findViewById(R.id.tvSure).setOnClickListener(v -> {
            webView.loadUrl(etURL.getText().toString());
            saveUrl(webView.getUrl());
        });
        button_open.setOnClickListener(v -> open());
    }


    /**
     * sp 存储 url
     * @param url
     */
    private void saveUrl(String url){
        sp.edit().putString("url",url).commit();
    }

    /*
     * sp 获取 url
     */
    private String getUrl(){
        return sp.getString("url",defUrl);
    }

    public void showWeightToJS(String weight){
        webView.loadUrl("javascript:showWeight("+weight+")");
    }

    public void showToastToJS(String str){
        webView.loadUrl("javascript:showToast("+90+")");
    }

    public class MyJavascriptInterface {
        //归零
        @JavascriptInterface
        public void jsoOrderZero(){
           orderZero();
        }
        //去皮
        @JavascriptInterface
        public void jsoOrderRemovePeel(){
            orderRemovePeel();
        }
    }

    private void orderZero(){
        serialPortUtils.sendSerialPort("SZ\r\n","UTF-8");
    }

    private void orderRemovePeel(){
        serialPortUtils.sendSerialPort("ST\r\n","UTF-8");
    }

    //
    void addLog(byte[] commbuf){
//        logList.add(new String(commbuf));
//        tvLog.setText(commbuf.toString());
    }

    void GetWeight(byte[] databuf)
    {
        int i,j,offset=6;
        boolean	StartFalg=false;
        scalenow.bZeroFlag=true;
        scalenow.bOverFlag=false;
        scalenow.bWeiStaFlag=false;
        switch(databuf[0])
        {
            case 'o':
            case 'O':
                scalenow.bOverFlag=true;
                break;
            case 'u':
            case 'U':
                scalenow.bWeiStaFlag=false;
                offset=6;	//6
                break;
            case 's':
            case 'S':
                scalenow.bWeiStaFlag=true;
                break;
        }
        if(databuf[5]=='-')offset=5;
        for(i=0;i<14;i++)
        {
            if(databuf[i+offset]=='\'')databuf[i+offset]='.';
            if(StartFalg)
            {
                if(((databuf[i+offset]>'9')||(databuf[i+offset]<'.'))&&(!((databuf[i+offset]==' ')&&(databuf[i+offset+1]<='9'))))
                {
                    break;
                }
            }
            else if((databuf[i+offset]>='0')&&(databuf[i+offset]<='9'))
            {
                StartFalg=true;
                if(databuf[i+offset]!='0')scalenow.bZeroFlag=false;
            }
        }
        scalenow.sformatNetWeight=new String(databuf,offset,i);


        for(j=0;j<6;j++)
        {
            if(databuf[i+j+offset]<0x20)
            {
                break;
            }
        }
        scalenow.sUnit=new String(databuf,i+offset,j);
    }

    public static class SCALENOW {
        public String		sformatNetWeight="0";
        public String		sUnit="0";
        public boolean bWeiStaFlag;
        public boolean bZeroFlag;
        public boolean bOverFlag;
    }

}
